<!-- src/components/SetObjectMetadataDrawer.vue -->
<template>
    <el-drawer :model-value="modelValue" :title="`设置文件元数据 - ${baseName}`" direction="rtl" size="50%"
        @close="$emit('update:modelValue', false)" @closed="$emit('closed')">
        <div v-if="loading" v-loading="loading" style="height: 100%;"></div>
        <div v-else class="drawer-content">
            <el-form :model="form" label-width="150px" ref="formRef" class="drawer-form">
                <el-form-item label="Content-Type" prop="ContentType">
                    <el-input v-model="form.ContentType" placeholder="例如: image/jpeg" />
                </el-form-item>
                <el-form-item label="Content-Encoding" prop="ContentEncoding">
                    <el-input v-model="form.ContentEncoding" placeholder="例如: gzip" />
                </el-form-item>
                <el-form-item label="Content-Language" prop="ContentLanguage">
                    <el-input v-model="form.ContentLanguage" placeholder="例如: en-US, zh-CN" />
                </el-form-item>
                <el-form-item label="Content-Disposition" prop="ContentDisposition">
                    <el-input v-model="form.ContentDisposition" placeholder="例如: attachment; filename= file.jpg" />
                </el-form-item>
                <el-form-item label="Cache-Control" prop="CacheControl">
                    <el-input v-model="form.CacheControl" placeholder="例如: max-age=3600" />
                </el-form-item>
                <el-form-item label="Expires" prop="Expires">
                    <el-date-picker v-model="form.Expires" type="datetime" placeholder="选择过期时间 (GMT)"
                        format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>

                <el-divider />

                <template v-if="!isBatchMode">
                    <el-divider />
                    <div class="custom-metadata-header">
                        <label>用户自定义元数据</label>
                        <el-button type="primary" link @click="addMetadataRow">添加</el-button>
                    </div>
                    <div v-if="customMetadata.length === 0" class="no-data-placeholder">没有数据</div>
                    <div v-if="customMetadata.length > 0" class="metadata-table-header">
                        <span class="header-key">参数</span><span class="header-value">值</span>
                    </div>
                    <div v-for="(item, index) in customMetadata" :key="index" class="metadata-row">
                        <el-input v-model="item.key" placeholder="my-key">
                            <template #prepend>{{ metadataPrefix }}</template>
                        </el-input>
                        <el-input v-model="item.value" placeholder="请输入值" class="meta-value-input" />
                        <el-button :icon="Delete" circle plain type="danger" @click="removeMetadataRow(index)" />
                    </div>
                </template>
            </el-form>

            <div class="drawer-footer">
                <el-button @click="$emit('update:modelValue', false)">取 消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">
                    确 定
                </el-button>
            </div>
        </div>
    </el-drawer>
</template>

<script setup>
// 这部分的逻辑与之前弹窗的逻辑完全相同
import { ref, watch, computed, nextTick } from 'vue';
import apiClient from '@/api';
import { ElMessage } from 'element-plus';
import { getBaseName } from '@/utils/formatters.js';
import { Delete } from '@element-plus/icons-vue';

const props = defineProps({
    modelValue: Boolean,
    bucketName: { type: String, required: true },
    objectKey: { type: String, default: null },
    mode: { type: String, default: 'single', validator: (value) => ['single', 'batch'].includes(value) },
    selectedItems: { type: Array, default: () => [] },
});
const emit = defineEmits(['update:modelValue', 'closed', 'success']);

const formRef = ref(null);
const loading = ref(false);
const isSubmitting = ref(false);

const form = ref({
    ContentType: '', ContentEncoding: '', ContentLanguage: '',
    ContentDisposition: '', CacheControl: '', Expires: null,
});
const customMetadata = ref([]);
const metadataPrefix = 'x-oss-meta-';

const isBatchMode = computed(() => props.mode === 'batch');
const baseName = computed(() => getBaseName(props.objectKey));
const drawerTitle = computed(() => {
    return isBatchMode.value ? `批量设置元数据 (共 ${props.selectedItems.length} 项)` : `设置文件元数据 - ${baseName.value}`;
});
const placeholderText = computed(() => isBatchMode.value ? '留空则不修改' : '请输入值');

const addMetadataRow = () => customMetadata.value.push({ key: '', value: '' });
const removeMetadataRow = (index) => customMetadata.value.splice(index, 1);

const fetchMetadata = async () => {
    loading.value = true;
    // 重置表单，防止上一次的数据残留
    form.value = { ContentType: '', ContentEncoding: '', ContentLanguage: '', ContentDisposition: '', CacheControl: '', Expires: null };
    customMetadata.value = [];
    try {
        const response = await apiClient.get(`/api/v1/buckets/${props.bucketName}/objects/details`, {
            params: { key: props.objectKey }
        });
        const details = response.data;

        // 1. 填充标准HTTP头
        const headers = details.http_headers;
        form.value.ContentType = headers.ContentType || details.content_type || '';
        form.value.ContentEncoding = headers.ContentEncoding || '';
        form.value.ContentLanguage = headers.ContentLanguage || '';
        form.value.ContentDisposition = headers.ContentDisposition || '';
        form.value.CacheControl = headers.CacheControl || '';
        form.value.Expires = headers.Expires ? new Date(headers.Expires) : null;

        // 2. 填充用户自定义元数据
        if (details.metadata) {
            customMetadata.value = Object.entries(details.metadata)
                // ======================= 【核心修复在这里】 =======================
                // 在映射之前，先过滤掉所有值为空字符串('')的条目
                .filter(([fullKey, value]) => value !== '')
                // ===============================================================
                .map(([fullKey, value]) => {
                    if (fullKey.toLowerCase().startsWith(metadataPrefix)) {
                        return { key: fullKey.substring(metadataPrefix.length), value: value };
                    }
                    return { key: fullKey, value: value };
                });
        }
    } catch (error) {
        console.error("获取元数据失败:", error);
        ElMessage.error('获取当前元数据失败');
        emit('update:modelValue', false);
    } finally {
        loading.value = false;
    }
};

watch(() => props.modelValue, (newVal) => {
    if (newVal) {
        // 关闭时重置表单
        form.value = { ContentType: '', ContentEncoding: '', ContentLanguage: '', ContentDisposition: '', CacheControl: '', Expires: null };
        customMetadata.value = [];

        // 只有在单个模式下才去获取已有数据
        if (!isBatchMode.value && props.objectKey) {
            fetchMetadata();
        }
    }
}, { immediate: true });

const handleSubmit = async () => {
    isSubmitting.value = true;
    if (isBatchMode.value) {
        await handleBatchSubmit();
    } else {
        await handleSingleSubmit();
    }
    isSubmitting.value = false;
};

const handleSingleSubmit = async () => {
    isSubmitting.value = true;
    try {
        // 1. 准备用户自定义元数据
        const userMetadataPayload = customMetadata.value
            .filter(item => item.key && item.value !== null) // 允许值为空字符串
            .reduce((acc, item) => {
                const fullKey = `${metadataPrefix}${item.key}`;
                acc[fullKey] = item.value;
                return acc;
            }, {});

        // 2. 准备完整的载荷
        const payload = {
            key: props.objectKey,
            headers: {
                ...form.value,
                Expires: form.value.Expires ? form.value.Expires.toUTCString() : null
            },
            metadata: userMetadataPayload
        };
        console.log(
            "【前端日志】准备发送给后端的完整 payload:",
            JSON.stringify(payload, null, 2)
        );
        // 3. 发送请求
        await apiClient.put(`/api/v1/buckets/${props.bucketName}/objects/metadata`, payload);

        ElMessage.success('元数据更新成功');
        emit('update:modelValue', false);
        emit('success');
    } catch (error) {
        console.error("更新元数据失败:", error);
        const errorMsg = error.response?.data?.error || '更新元数据失败，请重试';
        ElMessage.error(errorMsg);
    } finally {
        isSubmitting.value = false;
    }
};

const handleBatchSubmit = async () => {
    isSubmitting.value = true;
    try {
        const headersToUpdate = Object.entries(form.value).reduce((acc, [key, value]) => {
            if (value !== '' && value !== null) {
                acc[key] = (key === 'Expires') ? new Date(value).toUTCString() : value;
            }
            return acc;
        }, {});

        if (Object.keys(headersToUpdate).length === 0) {
            ElMessage.warning('您没有填写任何要修改的元数据');
            isSubmitting.value = false;
            return;
        }

        const payload = {
            keys: props.selectedItems.map(item => item.name),
            headers: headersToUpdate,
        };

        const response = await apiClient.put(`/api/v1/buckets/${props.bucketName}/objects/batch-metadata`, payload);

        // ... 成功/部分成功处理逻辑
        if (response.status === 207 && response.data.errors) {
            ElNotification({ title: '部分成功', message: response.data.message, type: 'warning', duration: 5000 });
        } else {
            ElMessage.success(response.data.message || '批量更新成功');
        }
        emit('update:modelValue', false);
        emit('success');
    } catch (error) {
        const errorMsg = error.response?.data?.error || '批量更新失败，请重试';
        ElMessage.error(errorMsg);
    } finally {
        isSubmitting.value = false;
    }
};
</script>

<style scoped>
.drawer-content {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.drawer-form {
    flex-grow: 1;
    overflow-y: auto;
    padding-right: 20px;
}

.drawer-footer {
    flex-shrink: 0;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color);
    display: flex;
    justify-content: flex-end;
}

/* 自定义元数据的样式保持不变 */
.custom-metadata-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.custom-metadata-header label {
    font-weight: 600;
    color: var(--el-text-color-regular);
}

.metadata-row {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.meta-key-input {
    margin-right: 10px;
}

.meta-value-input {
    margin-right: 10px;
}

.no-data-placeholder {
    color: var(--el-text-color-placeholder);
    text-align: center;
    padding: 20px;
    border: 1px dashed var(--el-border-color);
    border-radius: 4px;
    margin-bottom: 20px;
}

.metadata-table-header {
    display: flex;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 8px;
    padding-left: 110px;
    /* 与下方输入框对齐 */
}

.header-key {
    flex: 1;
}

.header-value {
    flex: 1;
    margin-left: 10px;
}

.metadata-row {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

/* 使用 flex 布局来控制输入框的宽度 */
.metadata-row .el-input {
    flex: 1;
}

.meta-value-input {
    margin-left: 10px;
    margin-right: 10px;
}
</style>